package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"post-master/cache"
	"post-master/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {

	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "标题或者内容为空",
		})
		return
	}

	data := models.Post{
		Title:   title,
		Content: content,
	}

	//mysql添加成功
	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	//redis写入数据
	var post models.Post
	models.DB.Where("id=?", data.ID).First(&post)
	jsonData, _ := json.Marshal(post)
	redis_data_key := "post_" + strconv.Itoa(int(data.ID))
	cache.Rdb.Set(cache.Ctx, redis_data_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {

	var posts []models.Post

	redis_data_key := "post_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_data_key).Result()
	if cacheData == "" {
		//从mysql读取数据
		models.DB.Find(&posts)
		//设置到缓存中
		jsonData, _ := json.Marshal(posts)
		cache.Rdb.Set(cache.Ctx, redis_data_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &posts)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": posts,
		"msg":  "success",
	})
	return
}

func Del(c *gin.Context) {
	id := c.Query("id")

	//删除mysql
	models.DB.Where("id=?", id).Delete(&models.Post{})

	//删除redis
	redis_data_key := "post_" + id
	cache.Rdb.Del(cache.Ctx, redis_data_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
